const ws = require("nodejs-websocket");
const moment = require('moment')
// YY年MM月DD日 HH时mm分ss秒
console.log("开始建立连接...")
const allUsers = {} //存储用户
const server = ws.createServer(function(conn) {
	//监听前端发送过来的信息
	conn.on("text", function(str) {
		obj = JSON.parse(str)
		let sendMes = null
		switch (obj.type) {
			case 1: {
				//用户发送信息
				sendMes = {
					username: obj.username,
					msg: obj.msg,
					date: moment().format("YYYY年MM月DD日 HH时mm分ss秒"),
					type: 1,
					userid: obj.userid
				}
				break
			}
			case 2: {
				//进入聊天
				// console.log(conn)
				allUsers[obj.userid] = conn
				console.log(Object.keys(allUsers).length + '个用户')
				sendMes = {
					username: obj.username,
					msg: obj.username + '进入聊天',
					date: moment().format("YYYY年MM月DD日 HH时mm分ss秒"),
					type: 2,
					userid: obj.userid
				}
				break
			}
		};
		//广播消息
		noticeEveryOne(sendMes)
		// conn.sendText("My name is Web Xiu!");
	})
	conn.on("close", function(code, reason) {
		console.log("关闭连接")
	});
	conn.on("error", function(code, reason) {
		console.log("异常关闭")
	});
}).listen(7890)

function noticeEveryOne(data) {
	server.connections.forEach(conn=>{
		conn.sendText(JSON.stringify(data));
	})
}
console.log("WebSocket建立完毕")
